function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +
                      '</a> Phone: (' + json.tmpo_poc_phone.substr(0,3) +
                      ') ' + json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
}


var vehicle_list = "";
var vehicleType_list = "";
var addingVehicle = 0;

function getVehicleTypes() {
    $.getJSON("/api/tmpo/vehicletype/",
        function(json){
            vehicleType_list = $(json.types);
        }
    );
}

function getVehicles() {
    vehicles_url = '/api/tmpo/vehicleinfo/';
    
    $.ajax({
        url: vehicles_url,
        type: "GET",
        dataType: "json",
        async: false,
        success: function(json){
            vehicle_list = $(json.vehicles);
        }
    });
}

function printVehicleRow(row) {

    var column1 = '<td ><span id="span_edit_' + row.id +
        '" class="hoverButton">Edit</span><span id="span_history_' +
        row.id + '" class="hoverButton" style="margin-top:15px;"'+
        '>History</span>' + row.vehicleno.replace(/"/g,"") + '</td>';
    var column2 = '<td >' + row.tagno + '</td>';
    var column3 = '<td align="center" ><a href="'+
        '/tmpo/vehicles/form1970/?id='+row.id+'"><img title='+
        '"Add Motor Equipment Utilization Record" width="16" height='+
        '"16" alt="Add Motor Equipment Utilization Record" src='+
        '"/tmpo/images/icons/form.gif"/></a></td>'; 
    var column4 = '<td >' + row.type + '</td>';
    var column5 = '<td >' + formatLargeNumbers(row.capacity) + '</td>';
    var column6 = '<td >' + row.doortype + '</td>';
    var column7 = '<td >' + formatLargeNumbers(row.weight) +'</td>';

    var column8 = '<td >' + ( (row.status == 'True')  ? 'On Hold </td>' : 
        'Available</td>') ;

    $("#vehicleLog").append('<tbody id="tbody_'+row.id+'"><tr>'+
    column1+column2+column3+column4+column5+column6+column7+column8+
    '</tr></tbody>');
}

function printVehicles() {
    $("#vehicleLog tbody").remove();
    if(!vehicle_list.length){
        $("#vehicleLog").append('<tbody><tr><td colspan="10"'+
        '>There are no vehicles currently listed</td></tr></tbody>');
    }else{
        jQuery.map(vehicle_list, function(row){
            printVehicleRow(row);
        });
    }
    $("#button_print").click(function() {
      $("#vehicleLog tbody tr td:nth-child(3)").remove();
      $("#vehicleLog thead tr th:nth-child(3)").remove();
      $("#vehicleLog tbody tr td:nth-child(1) span").remove();
      makePrinter("#vehicleLog")();
        return false;
//      resetTable();
    });
}

function setRowColors() {
    $("#vehicleLog tbody").removeClass('tableAlternateColor');
    $("#vehicleLog tbody:odd").addClass('tableAlternateColor');
}

function createDropdown(value) {
    var dropDown = "<select name='addType' id='addType'>";

        for (i=1;i<=vehicleType_list.length;i++)
        {
            if (value == vehicleType_list[i-1].description) {
                dropDown = dropDown+"<option selected value='"+i+"'>"+
                vehicleType_list[i-1].description;
            } else {
                dropDown = dropDown+"<option value='"+i+"'>"+
                vehicleType_list[i-1].description;
            }
        }
    dropDown = dropDown+"</select>";
    return dropDown;
}
function removeAddRow() {
    $("#addVehicle").remove();
    $("#addVehicleButtons").remove();
    addingVehicle = 0;
}

function removeEditRow() {
    $("#editVehicle").remove();
    $("#editVehicleButtons").remove();
}

function validateForm(last_btn) {

    var error_count = 0;
  
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("select[class='formError']").removeClass('formError');
    $("td > br").remove();
        
    var message_error_required = '<br><span class="errorMessage">' +
                'Please complete required field.</span>';
    var required_fields = ['VehicleNo','tagNo','capacity','doorType',
                           'weight'];                           
    jQuery.map(required_fields, function(field) { 
        if( !$("#"+field).val()) {
            error_count++;
            $("#"+field).parent().append(message_error_required);
            $("#"+field).parent().addClass("tableErrorColor");
            $("#"+field).addClass("formError");
        }
    });
        
    if(error_count){    
        $("#"+last_btn).after('<span class="generalErrorMessage'+
        '" name="message" id="message"><img alt="" src='+
        '"/tmpo/images/icons/alert.gif"/>'+
        'Please correct errors above to save vehicle data.</span>');
    } else {
        $("#message").remove();
        $("#"+last_btn).after(
            '<span id="message" name="message" class="waitMessage">'+
            '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
            'Your changes are being saved. Please wait.</span>');
        return true;
    }
    
}

function addVehicle() {

    var dataDict = {};
    dataDict.type = $("#addType").val();
    dataDict.vehicleno = $("#VehicleNo").val();
    dataDict.tagno = $("#tagNo").val();
    dataDict.capacity = $("#capacity").val();
    dataDict.weight = $("#weight").val();
    dataDict.doortype = $("#doorType").val();
    dataDict.status = ( ($("#status:checked").length) ? 1 : 0);
    
    $.ajax({
    url: "/api/tmpo/vehicles/",
    type: "PUT",
    data: dataDict,
    success: function() {
        console.debug("success");
        resetTable();
        },
    error: function(){
        console.debug("fail");
        }
    });
}

function updateVehicle(id) {
    var dataDict = {};
    dataDict.type = $("#addType").val();
    dataDict.vehicleno = $("#VehicleNo").val();
    dataDict.tagno = $("#tagNo").val();
    dataDict.capacity = $("#capacity").val();
    dataDict.weight = $("#weight").val();
    dataDict.doortype = $("#doorType").val();
    dataDict.status = ( ($("#status:checked").length) ? 1 : 0);
    
    $.ajax({
    url: "/api/tmpo/vehicles/"+id+"/",
    type: "POST",
    data: dataDict,
    success: function() {
        console.debug("success");
        resetTable();
        },
    error: function(){
        console.debug("fail");
        }
    });
}

function deleteVehicle(row) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url: '/api/tmpo/vehicles/'+row.id+'/',
            dataType: "text",
            success: function(){
              resetTable();
            }
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    };
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    $("#tbody_" + row.id + " tr").remove();
    $("#tbody_" + row.id).append('<tr><td colspan="10"><b>'+
    'This vehicle has been deleted. <span id="close_delete_' +
     row.id + '" class="inferLink"><u>Close</u></span> | <span id='+
     '"undo_delete_' + row.id + '" class="inferLink"><u>Undo</u>'+
     '</span></b></td></tr>');
    bindRows();
    $("#close_delete_" + row.id).click(function () {
        deleteCommitment(); 
        resetTable();
    });
    $("#undo_delete_" + row.id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        resetTable();
  
    });
}

function editVehicle(row) {
    $("#vehicleLog tbody").unbind();
    $("#vehicleLog tbody tr td").unbind();
	  toggleButtons(false);
    var editType = createDropdown(row.type);
    $("#tbody_" + row.id).replaceWith('<tbody id="tbody_'+row.id+
        '" class="highlight"><tr><td ><span id="span_edit_' + row.id +
        '" class="hoverButton">Edit</span><span id="span_history_' +
        row.id + '" class="hoverButton" style="margin-top:15px;">History'+
        '</span><input name="VehicleNo" type="text" size="12" id='+
        '"VehicleNo" value="'+row.vehicleno+'" /></td><td><input name='+
        '"tagNo" type="text" size="12" id="tagNo" value="'+row.tagno+
        '" /></td><td align="center" id="formDD1970"><a href='+
        '"/tmpo/vehicles/form1970/?id='+row.id+
        '"><img title="Add Motor Equipment Utilization Record" width='+
        '"16" height="16" alt="Add Motor Equipment Utilization Record"'+
        ' src="/tmpo/images/icons/form.gif"/></a></td><td >'+editType+
        '</td><td ><input type="text" size="12" name="capacity" id='+
        '"capacity" value="'+row.capacity+'" /></td><td><input name='+
        '"doorType" type="text" size="12" id="doorType" value="'+
        row.doortype+'" /></td><td><input name="weight" type="text" size='+
        '"12" id="weight" value="'+row.weight+'" /></td><td >On Hold '+
        '<input type="checkbox" id="status" name="status" >'+
        '</td></tr></tbody><tbody class="highlight" id='+
        '"editVehicleButtons" name="editVehicleButtons"><tr><td colspan='+
        '"9"><span id="button_save" name="button_save" class="button">'+
        '<img src="/tmpo/images/icons/save.gif" alt="">Save</span>'+
        '<span id="button_cancel" name="button_cancel" class="button">'+
        '<img src="/tmpo/images/icons/close.gif" alt="">Cancel</span>'+
        '<span id="button_delete" name="button_delete" class="button">'+
        '<img src="/tmpo/images/icons/delete.gif" alt="">Delete</span>'+
        '</td></tr></tbody>');
    (row.status == "True") ? $("#status").attr("checked","checked") : '';
    $("#span_edit_" + row.id).addClass('inactive');
    $("#span_history_" + row.id).click(
        function () { location.href = "/tmpo/vehicles/history/?id="+
        row.id; }
    );
    $("#button_cancel").click(
        function () {
			toggleButtons(true);
			resetTable(); }
        );
        
    $("#button_save").click(
        function(){
            if( validateForm('button_delete') )
            {  
				toggleButtons(true);
                updateVehicle(row.id);
            }
        });
        
    $("#button_delete").click(
        function () { 
            toggleButtons(true);
            deleteVehicle(row);
            $("#editVehicleButtons").remove();
		});
}

function printAddVehicleRow() {
    removeEditRow();
    var addType = createDropdown();
    $("#vehicleLog > tbody").unbind();    
    $("thead").after('<tbody class="tableActiveColor" name="addVehicle" id="addVehicle"><tr><td><input id="VehicleNo" value="" type="text" size="12" name="VehicleNo"></td><td><input id="tagNo" value="" type="text" size="12" name="tagNo"></td><td>&nbsp;</td><td>'+addType+'</td><td><input id="capacity" name="capacity" value="0" type="text" size="12"></td><td><input id="doorType" name="doorType" value="" type="text" size="12"></td><td><input id="weight" name="weight" value="0" type="text" size="12"></td><td >On Hold <input type="checkbox" id="status" name="status" ></td></tr></tbody><tbody class="tableActiveColor" id="addVehicleButtons" name="addVehicleButtons"><tr><td colspan="9" ><span id="button_save" name="button_save" class="button"><img src="/tmpo/images/icons/save.gif" alt="">Save</span><span id="button_cancel" name="button_cancel" class="button"><img src="/tmpo/images/icons/close.gif" alt="">Cancel</span></td></tr></tbody>');
}

function toggleButtons(x) {
	if (x===false){
		$("#addVehicleInline").unbind();
	    $("#button_print").unbind();
		$("#addVehicleInline").addClass('buttonInactive');
	    $("#button_print").addClass('buttonInactive');
	}else{
		$("#addVehicleInline").click( 
   			 function(){
        		 if (addingVehicle>0){
            		 $("#message").remove();
            		 $("#addVehicleCancel").after(
                        '<span class="generalErrorMessage" name="message"'+
                        ' id="message"><img alt="" src="/tmpo/images/icons'+
                        '/alert.gif"/>Only one vehicle may be added at a '+
                        'time.</span>');
        		 } else {
            		 addigVehicle = 1;
					 toggleButtons(false);
           		  	printAddVehicleRow();
          		   	$("#button_save").click(
          		  	 function(){
            		     if( validateForm('button_cancel') )
             		    {  
							 toggleButtons(true);
							 addVehicle();
              		    }
          		   	});
		
            		 $("#button_cancel").click(function(){
							toggleButtons(true);
							resetTable();});
        		 }
  		  });
		$("#button_print").click(function() {
	      	$("#vehicleLog tbody tr td:nth-child(3)").remove();
	      	$("#vehicleLog thead tr th:nth-child(3)").remove();
	      	$("#vehicleLog > tbody > tr > td:nth-child(1) > span").remove();
	      	makePrinter("#vehicleLog")();
	      	resetTable();
	    });
		$("#addVehicleInline").removeClass('buttonInactive');
		$("#button_print").removeClass('buttonInactive');
	}
}

function bindRows() {
    jQuery.map(vehicle_list, function(row){
      if( $("#tbody_"+row.id+":has[class!='highlight']").length ){
        $("#tbody_" + row.id).unbind();
        $("#tbody_" + row.id).hover(
            function () { $("#tbody_" + row.id).addClass('highlight'); },
            function () { $("#tbody_" + row.id).removeClass('highlight'); }
        );
        $("#span_history_"+ row.id).click(
        		function () {location.href = "/tmpo/vehicles/history/?id="+row.id;}
    	  );
    	  $("#span_edit_" + row.id).click(
            function () { editVehicle(row); }
        );
         $("#tbody_" + row.id + " tr td").click(
            function () { editVehicle(row); }
        );
       
       $("#tbody_" + row.id + " tr td span").parent().unbind();
        
      }   
        
   });
}

function resetTable() {
    removeAddRow();
    removeEditRow();
    vehicle_list = "";
    getVehicles();
    printVehicles();
    bindRows();
    setRowColors();
    addingVehicle = 0;
}

$(document).ready(function() {
    getSiteCfg();
    getVehicles();
    getVehicleTypes();
    printVehicles();
    bindRows();
    setRowColors();

    //map out button functionality
	
    $("#addVehicleInline").click( 
    function(){
         if (addingVehicle>0){
             $("#message").remove();
             $("#addVehicleCancel").after('<span class="generalErrorMessage" name="message" id="message"><img alt="" src="/tmpo/images/icons/alert.gif"/>Only one vehicle may be added at a time.</span>');
         } else {
             addingVehicle = 1;
			 toggleButtons(false);
             printAddVehicleRow();
             $("#button_save").click(
             function(){
                if( validateForm('button_cancel') ){  
                     toggleButtons(true);
					 addVehicle();
                  }
             });

             $("#button_cancel").click(function(){
					toggleButtons(true);
					resetTable();});
         }
    });
});